<?php

namespace GroupBuying;

use C\L\AdmController;
use C\M\GroupBuyingOrder;
use C\M\GroupBuyingUserOrder;
use C\M\User;

class OrderController extends AdmController
{
  /**
   * 列表、搜索接口
   **/
    public function indexAction()
    {
        $currentPage  = $this->request->getQuery('page', 'int', 1);
        $perPage      = $this->request->getQuery('per_page', 'int', 20);
        $orderSN      = $this->request->getQuery('order_sn', 'string', null);
        $goodsTitle   = $this->request->getQuery('goods_title', 'string', null);
        $state        = $this->request->getQuery('state', 'string', null);
        $startDate    = $this->request->getQuery('start_date', 'int', null);
        $endDate      = $this->request->getQuery('end_date', 'int', null);
        $type         = $this->request->getQuery('type', 'string', 'real');
        $userMobile   = $this->request->getQuery('user', 'string', null);
        $masterSlave  = $this->request->getQuery('master_slave', 'string', null);

        $columns = ['id', 'sn', 'state', 'amount', 'payment_amount', 'other_info', 'quantity', 'addtime'];
        $conditions = '1 = 1';
        $bind = [];

        switch ($type) {
            case 'real':
                $conditions .= ' AND user_id != :user_id:';
                $bind['user_id'] = 0;
                break;
            case 'generated':
                $conditions .= ' AND user_id = :user_id:';
                $bind['user_id'] = 0;
                break;
            default:
                break;
        }

        if ($orderSN) {
            $conditions .= ' AND sn LIKE :sn:';
            $bind['sn'] = '%' . $orderSN . '%';
        }
        if ($goodsTitle) {
            $conditions .= " AND JSON_EXTRACT(other_info, '$.goods.title') LIKE :goods_title:";
            $bind['goods_title'] = '%' . $goodsTitle . '%';
        }
        if ($state) {
            $conditions .= ' AND state = :state:';
            $bind['state'] = $state;
        }
        if ($startDate && $endDate) {
            $conditions .= ' AND addtime >= :start_date: AND addtime <= :end_date:';
            $bind['start_date'] = $startDate;
            $bind['end_date']   = $endDate;
        }
        if ($userMobile) {
            $user = User::findFirst("mobile = '$userMobile'");
            $conditions .= ' AND user_id = :filter_user_id:';
            $bind['filter_user_id'] = $user->uid ?? null;
        }
        if ($masterSlave && $masterSlave == 'master') {
            $conditions .= " AND JSON_EXTRACT(other_info, '$.is_master_order') = true";
        }
        if ($masterSlave && $masterSlave == 'slave') {
            $conditions .= " AND JSON_EXTRACT(other_info, '$.master_order_id') > 0";
        }

        $params =  [
            'conditions' => $conditions,
            'bind'       => $bind,
            'columns'    => $columns,
            'order'      => 'id DESC',
        ];
        $pagination = $this->getPagination($currentPage, $perPage, $params);

        $offset = ($currentPage - 1) * $perPage;
        $params['limit'] = [$perPage, $offset];
        $items = GroupBuyingOrder::find($params);

        // 整理结构
        $items = array_map(
            function ($item) {
                ['user' => $user, 'goods' => $goods] = json_decode($item['other_info'], true);
                $item['created_at'] = date('Y-m-d H:i:s', $item['addtime']);
                $item['user'] = $user;
                $item['goods'] = $goods;
                unset($item['other_info']);
                return $item;
            },
            $items->toArray()
        );

        $this->success(compact('pagination', 'items'));
    }

  /**
   * 详情接口
   **/
    public function showAction()
    {
        $id = $this->request->getQuery('id', 'int', 0);

        $order = GroupBuyingOrder::findFirst($id);

        [
        'user'         => $user,
        'goods'        => $goods,
        'commission'   => $commission,
        'group_buying' => $groupBuying,
        ] = json_decode($order->other_info, true);

        $currentJoinCount = GroupBuyingUserOrder::sum([
        'group_buying_order_id = ' . $order->id,
        'column' => 'quantity',
        ]);

        $result = [
        'order' => [
        'sn'                 => $order->sn,
        'current_join_count' => $currentJoinCount ?? 0,
        ],
        'group_buying' => [
        'quantity_min' => $groupBuying['quantity_min'] ?? null,
        'quantity_max' => $groupBuying['quantity_max'] ?? null,
        'period'       => $groupBuying['period'] ?? null,
        ],
        'user' => [
        'id'     => $user['id'] ?? null,
        'mobile' => $user['mobile'] ?? null,
        ],
        'goods' => [
        'thumbnail' => $goods['thumbnail'] ?? null,
        'title'     => $goods['title'] ?? null,
        'price'     => $goods['price'] ?? null,
        ],
        'commission' => [
        'rate'      => $commission['rate'] ?? null,
        'period'    => $commission['period'] ?? null,
        'type'      => $commission['type'] ?? null,
        'vip_bonus' => $commission['vip_bonus'] ?? null,
        ],
        ];

        return $this->success($result);
    }

    private function getPagination($currentPage, $perPage, $params)
    {
        $count = GroupBuyingOrder::count($params);

        $pagination = [
        'total'        => (int) $count,
        'per_page'     => (int) $perPage,
        'total_page'   => (int) ceil($count / $perPage),
        'current_page' => (int) $currentPage,
        ];

        return $pagination;
    }
}
